package com.itheima.sh.controller;

import com.itheima.sh.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("consumer")
public class ConsumerController {


    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod="queryByIdFallback")
    public User queryById(@PathVariable("id") String id){

        // 定义请求的url
//        String url = "http://127.0.0.1:8081/user/" + id;
//        Map usermap = restTemplate.getForObject(url, Map.class);


        // 基于 Eureka 调用
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//
//        String url = serviceInstance.getUri().toString();
//        System.out.println("url:" + url);
//
//        String urlconn = "http://"+host+":"+port+"/user/" + id;
//        Map usermap = restTemplate.getForObject(urlconn, Map.class);



        // 基于 Ribbon负载均衡调用
        String url = "http://user-service/user/" + id;

        if ("itheima".equals(id)) {
            throw new RuntimeException("itheima");
        }

        User user = restTemplate.getForObject(url, User.class);

        // ....


        return user;
    }


    public User queryByIdFallback(@PathVariable("id") String id) {

        User user = new User();
        user.setUsername(id);
        user.setName("-1 暂停服务");

        return user;
    }
}
